<template>
  <div>
    <el-form :model="spuInfo">
      <el-form-item label="SPU名称" label-width="120px" :model="spuInfo">
        <el-input v-model="spuInfo.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌" label-width="120px">
        <el-select placeholder="请选择品牌" v-model="spuInfo.tmId">
          <el-option
            :label="trade.tmName"
            v-for="trade in tradeMarkList"
            :key="trade.id"
            :value="trade.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU图片" label-width="120px">
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :file-list="spuImageList"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handlerSuccess"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="SPU描述" label-width="120px">
        <el-input type="textarea" v-model="spuInfo.description"></el-input>
      </el-form-item>
      <el-form-item label="销售属性" label-width="120px">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            v-for="attr in unSelectSaleAttr"
            :key="attr.id"
            :value="`${attr.id}:${attr.name}`"
            :label="attr.name"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          style="margin-left: 10px"
          @click="addAttr"
          :disabled="!attrIdAndAttrName"
          >添加销售属性</el-button
        >
        <el-table class="margin" border :data="spuInfo.spuSaleAttrList">
          <el-table-column label="序号" type="index"></el-table-column>
          <el-table-column
            label="属性名"
            prop="saleAttrName"
            width="100px"
          ></el-table-column>
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row }">
              <el-tag
                style="margin-left: 10px  display: flex;"
                v-for="(saleValue, index) in row.spuSaleAttrValueList"
                :key="saleValue.id"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ saleValue.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model.trim="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >+ 添加属性</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template slot-scope="{ $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spuInfo.spuSaleAttrList.splice($index, 1)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveSpuInfo">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      spuInfo: {
        category3Id: 0,
        description: "",
        id: 0,
        spuImageList: [
          {
            id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0,
          },
        ],
        spuName: "",
        //平台属性与属性值收集
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "",
                saleAttrName: "",
                saleAttrValueName: "",
                spuId: 0,
              },
            ],
          },
        ],
        tmId: "",
      },
      tradeMarkList: [],
      spuImageList: [],
      saleAttrList: [],
      attrIdAndAttrName: "",
    };
  },
  methods: {
    async getSpuInfo(spuId) {
      const res = await this.$Api.spu.reqSpu(spuId);
      this.spuInfo = res.data;
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.spuImg = fileList;
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 图片上传
    handlerSuccess(response, file, fileList) {
      if (response.code !== 200) {
        this.$message.error("图片上传失败");
      } else {
        this.spuImageList = fileList;
      }
    },
    cancel() {
      this.$emit("cancel", 0);
      this.attrIdAndAttrName = "";
      Object.assign(this._data, this.$options.data());
    },
    // 获取品牌信息
    async getTradeMarkList(category3Id) {
      this.spuInfo.category3Id = category3Id;
      const res = await this.$Api.spu.reqTradeMarkList();
      this.tradeMarkList = res.data;
    },
    async getSpuImg(spuId) {
      const res = await this.$Api.spu.reqSpuImageList(spuId);
      this.spuImageList = res.data;
      this.spuImageList.forEach((item) => {
        item.name = item.imgName;
        item.url = item.imgUrl;
      });
    },
    // 获取全部商品属性
    async getSaleAttrList() {
      const res = await this.$Api.spu.reqBaseSaleAttrList();
      this.saleAttrList = res.data;
    },
    // 点击删除 Tag 图标
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },

    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // input 离焦事件
    handleInputConfirm(row) {
      if (row.inputValue.trim()) {
        // 新增的属性值
        const { baseSaleAttrId, inputValue } = row;
        // 不能存在两个相同的值
        let result = row.spuSaleAttrValueList.every(
          (item) => item.saleAttrValueName !== inputValue
        );
        if (result) {
          let newSaleAttrValue = {
            baseSaleAttrId,
            saleAttrValueName: inputValue,
          };
          row.spuSaleAttrValueList.push(newSaleAttrValue);
        } else {
          this.$message.error("不能存在两个相同的值");
          row.inputVisible = false;
          row.inputValue = "";
        }
      }
      row.inputVisible = false;
      row.inputValue = "";
    },
    // 添加属性
    addAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      };
      this.spuInfo.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndAttrName = "";
    },
    // 保存按钮
    async saveSpuInfo() {
      if (this.spuInfo.spuName == "" || this.spuInfo.description == "")
        return this.$message.error("表单存在必选项");
      this.spuInfo.spuImageList = this.spuImageList.map((item) => {
        return {
          imgName: item.name,
          imgUrl: (item.response && item.response.data) || item.url,
        };
      });
      try {
        const res = await this.$Api.spu.reqSaveOrUpdateSpu(this.spuInfo);
        if (res.code == 200) {
          this.$message.success("保存成功");
          // 清除数据
          Object.assign(this._data, this.$options.data());
          // 如果有ID 则是修改后的保存 反之是添加后的保存
          if (this.spuInfo.id) {
            this.$emit("cancel", 0, { flag: "修改" });
          } else {
            this.$emit("cancel", 0, { flag: "添加" });
          }
        }
      } catch (error) {
        this.$message.error("保存失败");
      }
    },
  },
  computed: {
    //计算出还未选择的销售属性
    unSelectSaleAttr() {
      //整个平台的销售属性一共三个：尺寸、颜色、版本 ----saleAttrList
      //当前SPU拥有的属于自己的销售属性SPU.spuSaleAttrList  ----颜色
      //数组的过滤方法，可以从已有的数组当中过滤出用户需要的元素，并未返回一个新的数据
      let result = this.saleAttrList.filter((item) => {
        //every数组的方法，会返回一个布尔值【真，假的】
        return this.spuInfo.spuSaleAttrList.every((item1) => {
          return item.name != item1.saleAttrName;
        });
      });
      return result;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-table .cell {
  display: flex;
  flex-wrap: wrap;
}
</style>
